package com.rong.mbt.personal.activity;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.calanger.hh.entity.ResultView;
import com.calanger.hh.model.ImgUrl;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.base.PBaseActivity;
import com.rong.mbt.personal.adapter.NineImgAdapter;
import com.rong.mbt.personal.dialog.pickerDialog.GlideImageLoader;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.SpUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MedicalRecordAddActivity extends PBaseActivity {

    protected Context mContext;
    private TextView tvYzm;

//    @BindView(R.id.et_medical_record_title)
    private EditText etMedicalRecordTitle;
//    @BindView(R.id.et_medical_record_info)
    private EditText etMedicalRecordInfo;
    private ImageView commonIvImgAdd;
    private LinearLayout llWindLayout;
    private Button btMedicalRecordSubmit;

    private GridView gvImgShowNine;
    private NineImgAdapter nineImgAdapter;

    private String title;
    private String info;
    private List<File> fileList = new ArrayList<File>();;
    private GalleryConfig galleryConfig;
    private List<String> path = new ArrayList<>();
    private Dialog dialog_photo;
    ArrayList<ImgUrl> list = new ArrayList<ImgUrl>();
    private String imgAddUrl;


    @Override
    public int getLayoutId() {
        return R.layout.activity_add_medical_record;
    }

    @Override
    public void initView() {
        super.initView();
        mContext = this;

        findView();
        listener();

    }




    public void checkOk() {
        title = etMedicalRecordTitle.getText().toString();
        info = etMedicalRecordInfo.getText().toString();

    }

    private void myOnclick() {
        nineImgAdapter.delete(new NineImgAdapter.Det() {
            @Override
            public void del(int position) {
//              删除list中的数据，重新绑定数据
                list.remove(position);
                nineImgAdapter.notifyDataSetChanged();
            }
        });
    }

    @SuppressLint("ResourceType")
    private void findView() {
        gvImgShowNine  = findViewById(R.id.gv_img_show_nine);

        ImgUrl imgUrl = new ImgUrl();
        imgUrl.setRemarker("add");
        list.add(imgUrl);
        nineImgAdapter = new NineImgAdapter(list,this);

        gvImgShowNine.setAdapter(nineImgAdapter);

        myOnclick();
        gvImgShowNine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ImgUrl imgUrl = (ImgUrl) nineImgAdapter.getItem(position);
                if("add".equalsIgnoreCase(imgUrl.getRemarker())){
                    photoDialog();
                }
                else{
                    //放大
                }
            }
        });




        etMedicalRecordTitle  = findViewById(R.id.et_medical_record_title);
        etMedicalRecordInfo  = findViewById(R.id.et_medical_record_info);

        TextView tvTitle = findViewById(R.id.header_center_text);
        tvTitle.setText("添加病历");
        commonIvImgAdd = findViewById(R.id.common_iv_img_add);
        llWindLayout  = findViewById(R.id.iiiimmmm);
//        findViewById(R.id.head_blue_iv_right).setVisibility(View.GONE);

        btMedicalRecordSubmit  = findViewById(R.id.bt_medical_record_submit);

        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sj.hh.FileProvider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
//                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(true, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
//                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();

    }

    private void listener() {
        findViewById(R.id.ll_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        findViewById(R.id.common_iv_img_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                photoDialog();
            }
        });


        findViewById(R.id.bt_medical_record_submit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkOk();

                OkGo.<ResultView>post(UrlApi.medicalRecordAdd)
                        .tag(this)
                        .headers("mbtToken", SpUtils.getToken(getApplicationContext()))
                        .params("title", title)
                        .params("info", info)
                        .addFileParams("file",fileList)
                        .execute(new JsonCallback<ResultView>(){
                            @Override
                            public void onSuccess(Response<ResultView> response) {
                                Log.i("test", "onSuccess  " + response.body());
                                ResultView resultView = response.body();
                                if (resultView.getResultCode() == 0) {
                                    Toast.makeText(MedicalRecordAddActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                    finish();
                                } else {
                                    Toast.makeText(MedicalRecordAddActivity.this, resultView.getMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }

                            @Override
                            public void onError(Response<ResultView> response) {
                                super.onError(response);
                                Log.i("test", "onError  " + response.message());
                                Toast.makeText(MedicalRecordAddActivity.this, response.message(), Toast.LENGTH_SHORT).show();
                            }

                        });
            }
        });


    }

    private IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {

        @Override
        public void onStart() {

        }

        @Override
        public void onSuccess(List<String> photoList) {
            path = photoList;
            for(String fileName:photoList){
                Log.i("fileName",fileName);
                File file = new File(fileName);
                fileList.add(file);
                ImgUrl imgUrl = new ImgUrl();
                imgUrl.setImgUrl(fileName);
                list = new ArrayList<ImgUrl>();
                list.add(imgUrl);
                if(photoList.size()<9){
                    ImgUrl imgUrlAdd = new ImgUrl();
                    imgUrlAdd.setImgUrl(imgAddUrl);
                    imgUrlAdd.setRemarker("add");
                    list.add(imgUrlAdd);
                }
            }
            nineImgAdapter.setData(list);
            nineImgAdapter.notifyDataSetChanged();
//            gvImgShowNine.setAdapter(nineImgAdapter);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onFinish() {

        }

        @Override
        public void onError() {

        }
    };


    private void photoDialog() {
        dialog_photo = new Dialog(this, com.rong.mbt.personal.R.style.photo_dialog);
        View view = LayoutInflater.from(this).inflate(com.rong.mbt.personal.R.layout.dialog_take_photo, null);
        dialog_photo.setContentView(view);
        Window window = dialog_photo.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(com.rong.mbt.personal.R.style.bottomDialogStyle);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        if (!dialog_photo.isShowing()) {
            dialog_photo.show();
        }
        view.findViewById(com.rong.mbt.personal.R.id.tv_open_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                } else {
                }
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(MedicalRecordAddActivity.this);
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_choose_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_photo.dismiss();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                } else {
                }
                GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(MedicalRecordAddActivity.this);
            }
        });
        view.findViewById(com.rong.mbt.personal.R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog_photo.isShowing()) {
                    dialog_photo.hide();
                }
            }
        });
    }

}
